<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use think\facade\Db;
use app\common\facade\model\MaterialModel; // 引入素材类模型门面代理
use app\common\facade\model\ChannelInfoModel; // 引入频道模型门面
use app\common\facade\model\PgmListModel; // 引入编单门面
use app\common\facade\model\PgmListDetailModel; // 引入编单门面
use app\common\facade\model\AdvPgmListModel; // 引入广告节目单表
use app\common\facade\model\AdvPgmListDetailModel; // 广告节目单详情表
use app\common\facade\model\PgmInfoDetailModel; // 节目库播出明细表
use app\common\facade\model\PlayListModel; // 引入播出单主表模型
use app\common\facade\model\PlayListDetailModel; // 引入播出单明细表模型

class PlayEditroom extends BaseAdmin
{
    public function pgmplaydatelist($param)
    {
        $where = [];
        if(empty($param['channel_id']) || !isset($param['channel_id'])) {
            exception('频道参数异常');
        }
        $where[] = ['channel_id', '=', $param['channel_id']];
        $where[] = ['pgmlist_date', '>=', date('Y-m-d', time())];
        $where[] = ['check_flag', '=', 1];
        $res = PgmListModel::where($where)->select()->toArray();

        // todo 获取总编室已审核通过的编单
        $weekarray=array("日","一","二","三","四","五","六");
        if(!empty($res)){
            $data = [];
            foreach($res as $k => $v) {
                $data[$k]['label'] = $v['pgmlist_date']. ' [星期'. $weekarray[date("w",strtotime($v['pgmlist_date']))].']';
                $data[$k]['value'] = $v['pgmlist_date'];
            }
            return $data;
        } else {
            return [];
        }
    }

    public function pgmplaydateadd($param)
    {
        /*
         * 1, 先查询播出表是否已经创建过编单, 有则删除重新写入
         * 2, 查询总编单主表记录，获取主键pgmlist_id, 根据pgmlist_id 查找总编单明细表编单记录.
         * 3, 删除播出编单明细表主键为pgmlist_id 的所有记录.
         * 3, 将编单记录写入播出单明细表中。完成编单拷贝。 
         */
        if(!isset($param['channel_id']) || !isset($param['pl_date'])) {
            exception('参数异常！');
        }
        $where = [];
        $where[] = ['pl_date', '=', $param['pl_date']];
        $where[] = ['channel_id', '=', $param['channel_id']];
        // 启用事务
        Db::startTrans();
        try{
            if ($res = PlayListModel::info($where)) {
                // 删除播出串联单
                PlayListModel::deleteData([['pgmlist_id', '=', $res['pgmlist_id']]]);
                // 删除播出串联单明细
                PlayListDetailModel::deleteData([['pgmlist_id', '=', $res['pgmlist_id']]]);
            }
    
            $pgmListRes = PgmListModel::info([
                ['pgmlist_date', '=', $param['pl_date']],
                ['channel_id', '=', $param['channel_id']],
                ['check_flag', '=', '1']
            ]);
    
            if(empty($pgmListRes)) {
                exception('总编单不存在,或未审核通过！');
            }
            $nid = PlayListModel::insertGetId($param);
    
            $pgmlistDetail = PgmListDetailModel::where([
                ['pgmlist_id', '=', $pgmListRes['pgmlist_id']]
            ])->order('seq Asc')->select()->toArray();
    
            foreach($pgmlistDetail as &$v) {
                unset($v['play_time']);
                $v['pgmlist_id'] = $nid;
            }
            PlayListDetailModel::insertAll($pgmlistDetail);
            Db::commit();
            return $nid ?:false;
        } catch(\Exception $e) {
            // var_dump(PlayListDetailModel::getLastSql());
            Db::rollback();
            exception($e->getMessage(), $e->getCode());
        }        
    }

    public function playchannelpgm($param)
    {
        $channel_list = ChannelInfoModel::listsAll()->toArray();

        $where = [];
        if($param['day'] == 'depart') { //  只显示昨天以后的编单
            $beforeDay = date('Y-m-d', time() - 86400);
            $where[] = ['pl_date', '>=', $beforeDay];
        }

        $pgmroom_list = PlayListModel::listsAll($where, [], 'pl_date asc')->toArray();
        $data = [];
        if($channel_list) {
            foreach($channel_list as $k => $v) {
                $data[$k]['value'] = $v['id'];
                $data[$k]['keyindex'] = $v['id'].'-channel';
                $data[$k]['label'] = $v['channel_name'];
            }

            foreach($pgmroom_list as &$c) {
                foreach($data as $d =>$f) {
                    if($c['channel_id'] == $f['value']) {
                        $data[$d]['children'][] = ['value' => $c['pgmlist_id'], 'keyindex' => $c['pgmlist_id'], 'label' => $c['pl_date'], 'check_flag' => 2];
                    }
                }
            }
        }
        return $data;
    }

    public function playchannelpgmDel($ids)
    {
        $pgmlist_id = $ids[0];
        $where = [];
        $where[] = ['pgmlist_id', '=', $pgmlist_id];
        if(!empty($ids)) {
            Db::startTrans();
            try {
                PlayListModel::deleteData($where);
                PlayListDetailModel::deleteData($where);
                Db::commit();
                return ['code'=> 1, 'msg' => '删除成功!'];
            } catch(\Exception $e) {
                Db::rollback();
                exception($e->getMessage(), $e->getCode());
            }
        }
    }

    public function playchanneldetail($param)
    {
        if (!isset($param['type'])) exception('节目组参数异常!');

        $where = [];
        $where[] = ['pgmlist_id', '=', $param['type']]; 

        return PlayListDetailModel::detailLists($where);
    }

    public function pgmplaystate($param)
    {
        if(!isset($param['channel_id']) || !isset($param['pl_date'])) {
            exception('参数异常！');
        }
        $where = [];
        $where[] = ['pl_date', '=', $param['pl_date']];
        $where[] = ['channel_id', '=', $param['channel_id']];

        return empty(PlayListModel::info($where)) ? false : true;
    }

    // 播出串联单编辑保存
    public function pgmdetailAddEdit($params) 
    {
        if(!empty($params)) {
            // 启动事务
            Db::startTrans();
            $insert_data = [];
            $update_data = [];

            foreach($params as &$v) {
                $where = [];
                $where[] = ['pgmlist_id', '=', $v['pgmlist_id']];
                $where[] = ['seq', '=', $v['seq']];
                if(PlayListDetailModel::info($where)) {
                    $update_data[] = $v;
                    // PlayListDetailModel::addEditSave($v, $where);
                } else {
                    $insert_data[] = $v;
                    // PlayListDetailModel::create($v);
                }
            }

            try {
                if(!empty($insert_data)) {
                    PlayListDetailModel::insertAll($insert_data);
                }

                if(!empty($update_data)) {
                    foreach($update_data as &$x) {
                        $upwhere = [];
                        $upwhere[] = ['pgmlist_id', '=', $x['pgmlist_id']];
                        $upwhere[] = ['seq', '=', $x['seq']];
                        PlayListDetailModel::addEditSave($x, $upwhere);
                    }
                }
                // 提交事务
                Db::commit();
                return true;
            } catch(\Exception $e) {
                Db::rollback();
                exception($e->getMessage(), $e->getCode());
            }
        }
    }

    public function pgmdetailDel($ids)
    {
        $pgmlist_id = $ids[0]; 
        unset($ids[0]);
        $where = [];
        $where[] = ['pgmlist_id', '=', $pgmlist_id];
        if(!empty($ids)) {
            $where[] = ['seq', 'not in', $ids];
            PlayListDetailModel::deleteData($where);
        } else {
            PlayListDetailModel::deleteData($where);
        }

        return true;
    }
}